package com.jt.blog.interceptor;

import com.jt.blog.common.model.Response;
import com.jt.blog.model.User;
import com.jt.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author : 戴瑞
 * @Description :
 * @create : 2018-03-31 14:39
 **/

public class InitInterception extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String pathVariable = (String) request.getAttribute("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping");
        String username = "admin";
        if (pathVariable.equals("/"))
            username = "admin";
        else {
            username = pathVariable.substring(1);
        }
        // 根据用户名来查询博主的ID
        Response<User> userResponse = userService.selectByUserName(username);
        HttpSession session = request.getSession();
        if (userResponse.isSuccess()) {
            session.setAttribute("userId", userResponse.getResult().getId());
            return true;
        } else {
            throw new RuntimeException("没有该用户");
        }
    }
}
